package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.GmElecCostInfo;
import com.ruoyi.system.domain.GmTenantInfo;
import com.ruoyi.system.mapper.GmElecCostMapper;
import com.ruoyi.system.service.IGmElecCostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * 国贸电费管理Service业务层处理
 *
 * @author xty
 * @date 2021-12-10
 */

@Service
public class GmElecCostServiceImpl implements IGmElecCostService {

    @Autowired
    private GmElecCostMapper elecCostMapper;

    @Override
    public List<GmElecCostInfo> selectAllGmElecCost() {
        return elecCostMapper.selectAllGmElecCost();
    }

    /**
     * 条件查询list页面显示信息
     *
     * @param elecCostInfo 电费info
     * @return 电费list
     * */
    @Override
    public List<GmElecCostInfo> selectGmElecCostInfoList(GmElecCostInfo elecCostInfo) {
        return elecCostMapper.selectGmTenantInfoList(elecCostInfo);
    }

    /**
     * 插入一条elecCostinfo数据
     *
     * @param elecCostInfo 电费info
     * @return 结果
     */
    @Override
    public int insertGmElecCostInfo(GmElecCostInfo elecCostInfo) {
        countTotalData(elecCostInfo);
        elecCostInfo.setElecCostId(UUID.randomUUID().toString().replaceAll("-", ""));
//        elecCostInfo.setElecMonth(getMonth(elecCostInfo.getCheckMeterTime()));
        elecCostInfo.setElecMonth(elecCostInfo.getElecMonth());
        return elecCostMapper.insertGmElecCostInfo(elecCostInfo);
    }

    /**
     * 根据获取的数值计算电表集合和金额
     *
     *  @param elecCostId 电费info的ID
     *  @return GmElecCostInfo 单条数据
     *
     */
    @Override
    public GmElecCostInfo selectGmElecCostInfoById(String elecCostId) {
        return elecCostMapper.selectGmElecCostInfoById(elecCostId);
    }

    /**
     * 修改一条elecCostinfo数据
     *
     * @param elecCostInfo 电费info
     * @return 结果
     */
    @Override
    public int updateGmElecCostInfo(GmElecCostInfo elecCostInfo) {
        countTotalData(elecCostInfo);
//        elecCostInfo.setElecMonth(getMonth(elecCostInfo.getCheckMeterTime()));
        return elecCostMapper.updateGmElecCostInfo(elecCostInfo);
    }

    /**
     * 删除电费管理对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteGmElecCostByIds(String ids) {
        return elecCostMapper.deleteGmElecCostByIds(Convert.toStrArray(ids));
    }
    /* 月查 */
    @Override
    public List<GmElecCostInfo> selectGmElecCostByMonth(String elecMonth) {
        return elecCostMapper.selectGmElecCostByMonth(elecMonth);
    }

    /* 名查 */
    @Override
    public List<GmElecCostInfo> selectGmElecCostByCName(String companyName) {
        return elecCostMapper.selectGmElecCostByCName(companyName);
    }

    /**
     *校验Excel数据是否满足条件
     *
     * @param lists
     * @return
     */
    @Override
    public String validateDatas(List<GmElecCostInfo> lists) {
        StringBuilder sb =new StringBuilder();
        String regex = "^(20|19){1}[0-9]{2}(((0){1}[1-9]{1})|((1){1}(0|1|2){1}))$";
        if (StringUtils.isEmpty(lists)){
            sb.append("excel中无任何数据，请确认文件！");
        }else {
            for (int i = 0; i <lists.size() ; i++) {
                /* ABCD抄表无数据null填充 */
                if (lists.get(i).getDegreePreA() == null){
                    lists.get(i).setDegreePreA(0.0);
                }
                if (lists.get(i).getDegreePreB() == null){
                    lists.get(i).setDegreePreB(0.0);
                }
                if (lists.get(i).getDegreePreC() == null){
                    lists.get(i).setDegreePreC(0.0);
                }
                if (lists.get(i).getDegreePreD() == null){
                    lists.get(i).setDegreePreD(0.0);
                }
                if (lists.get(i).getDegreeIssueA() == null){
                    lists.get(i).setDegreeIssueA(0.0);
                }
                if (lists.get(i).getDegreeIssueB() == null){
                    lists.get(i).setDegreeIssueB(0.0);
                }
                if (lists.get(i).getDegreeIssueC() == null){
                    lists.get(i).setDegreeIssueC(0.0);
                }
                if (lists.get(i).getDegreeIssueD() == null){
                    lists.get(i).setDegreeIssueD(0.0);
                }
                /* 数据判断 */
                if (StringUtils.isBlank(lists.get(i).getCompanyName())){
                    sb.append("第"+(i+1)+"行、用户单位名称为空！<br/>");
                }
                if (StringUtils.isBlank(lists.get(i).getProjectName())){
                    sb.append("第"+(i+1)+"行、项目名称为空！<br/>");
                }
                if (StringUtils.isBlank(lists.get(i).getFloorName())){
                    sb.append("第"+(i+1)+"行、楼层号为空！<br/>");
                }
                if (StringUtils.isBlank(lists.get(i).getRoomNumber())){
                    sb.append("第"+(i+1)+"行、房号为空！<br/>");
                }
                if (StringUtils.isBlank(lists.get(i).getElecMonth())){
                    sb.append("第"+(i+1)+"行、电费月份为空！<br/>");
                }
                if (!Pattern.matches(regex, lists.get(i).getElecMonth())){
                    sb.append("第"+(i+1)+"行、电费月份不符合格式！<br/>");
                }
                if (!lists.get(0).getElecMonth().equals(lists.get(i).getElecMonth())){
                    sb.append("第"+(i+1)+"行、电费月份不符合导入的时间批次！<br/>");
                }
//                if (!getMonth(lists.get(i).getCheckMeterTime()).equals(lists.get(i).getElecMonth())){
//                    sb.append("第"+(i+1)+"行、电费月份与抄表时间不服！<br/>");
//                }
                if (Double.isNaN(lists.get(i).getElecRate())){
                    sb.append("第"+(i+1)+"行、电费乘率为空！<br/>");
                }
                if (Double.isNaN(lists.get(i).getElecUnitPrice())){
                    sb.append("第"+(i+1)+"行、电费单价为空！<br/>");
                }
            }
        }
        if (sb.length()>0){
            return sb.toString();
        };
        return "";
    }

    /**
     * 导入员工合同关系
     * @param lists
     * @param updateSupport
     * @param sysUser
     * @return
     */
    @Override
    public String importRelations(List<GmElecCostInfo> lists, boolean updateSupport, SysUser sysUser) {
        int successNum = 0;
        int failureNum = 0;
        StringBuffer successMsg = new StringBuffer();
        StringBuffer failureMsg = new StringBuffer();
        for (GmElecCostInfo sb:lists){
            countTotalData(sb);
            try {
                if (StringUtils.isNotEmpty(sb.getElecCostId())){
                    elecCostMapper.updateGmElecCostInfo(sb);
                    if (elecCostMapper.selectGmElecCostInfoById(sb.getElecCostId()).getCompanyName() == null) {
                        elecCostMapper.insertGmElecCostInfo(sb);
                    }else {
                        elecCostMapper.updateGmElecCostInfo(sb);
                    }
                }else {
                    sb.setElecCostId(UUID.randomUUID().toString().replaceAll("-", ""));
//                    sb.setElecMonth(getMonth(sb.getCheckMeterTime()));
                    elecCostMapper.insertGmElecCostInfo(sb);
                }
                successNum++;
                successMsg.append("<br/>第" + (successNum+failureNum) + "条、" + sb.getElecCostId() + "导入成功");
            }catch (Exception e){
                failureNum ++;
                failureMsg.append("<br/>第"+(successNum+failureNum)+"条、导入失败");
            }

        }
        if(failureNum > 0){
            failureMsg.insert(0, "很抱歉，导入失败！共"+failureNum+"条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }else {
            successMsg.insert(0, "恭喜您数据已全部导入成功！共"+ successNum +"条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public int removeGmElecCostByMonth(String elecMonth) {
        return elecCostMapper.removeGmElecCostByMonth(elecMonth);
    }


    /**
     * 抽年月时间
     * */
    public String getMonth(Date date){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        return new String(sdf.format(date));
    }


    /**
     * 根据抄表数据计算总电量和金额
     * modify by bzs 20220303
     * */
    public void countTotalData(GmElecCostInfo elecCostInfo){
        BigDecimal degreeAbd = new BigDecimal(Double.toString(elecCostInfo.getDegreeIssueA())).subtract(new BigDecimal(Double.toString(elecCostInfo.getDegreePreA())));
        Double degreeA = degreeAbd.doubleValue();
        elecCostInfo.setDegreeA(degreeA);
        BigDecimal degreeBbd = new BigDecimal(Double.toString(elecCostInfo.getDegreeIssueB())).subtract(new BigDecimal(Double.toString(elecCostInfo.getDegreePreB())));
        Double degreeB = degreeBbd.doubleValue();
        elecCostInfo.setDegreeB(degreeB);
        BigDecimal degreeCbd = new BigDecimal(Double.toString(elecCostInfo.getDegreeIssueC())).subtract(new BigDecimal(Double.toString(elecCostInfo.getDegreePreC())));
        Double degreeC = degreeCbd.doubleValue();
        elecCostInfo.setDegreeC(degreeC);
        BigDecimal degreeDbd = new BigDecimal(Double.toString(elecCostInfo.getDegreeIssueD())).subtract(new BigDecimal(Double.toString(elecCostInfo.getDegreePreD())));
        Double degreeD = degreeDbd.doubleValue();
        elecCostInfo.setDegreeD(degreeD);
        /*总度数*/
        BigDecimal degreebd = degreeAbd.add(degreeBbd).add(degreeCbd).add(degreeDbd);
        Double degree = degreebd.doubleValue();
        /*总电费*/
        BigDecimal elecTotalPricebd = new BigDecimal(Double.toString(elecCostInfo.getElecRate())).multiply(new BigDecimal(Double.toString(elecCostInfo.getElecUnitPrice()))).multiply(degreebd);
        Double elecTotalPrice = elecTotalPricebd.setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
        /*总上月电表电数 */
        BigDecimal degreePrebd = new BigDecimal(Double.toString(elecCostInfo.getDegreePreA())).add(new BigDecimal(Double.toString(elecCostInfo.getDegreePreB()))).add(new BigDecimal(Double.toString(elecCostInfo.getDegreePreC()))).add(new BigDecimal(Double.toString(elecCostInfo.getDegreePreD())));
        Double degreePre = degreePrebd.doubleValue();
        elecCostInfo.setDegreePre(degreePre);
        /*总本月电表电数 */
        BigDecimal degreeIssuebd = new BigDecimal(Double.toString(elecCostInfo.getDegreeIssueA())).add(new BigDecimal(Double.toString(elecCostInfo.getDegreeIssueB()))).add(new BigDecimal(Double.toString(elecCostInfo.getDegreeIssueC()))).add(new BigDecimal(Double.toString(elecCostInfo.getDegreeIssueD())));
        Double degreeIssue = degreeIssuebd.doubleValue();
        elecCostInfo.setDegreeIssue(degreeIssue);
        /*总实用电数 */
        elecCostInfo.setDegree(degree);
        /*总金额 = 实用电数 * 费率 * 单价 */
        elecCostInfo.setElecTotalPrice(elecTotalPrice);
    }
}
